import http from '../../utils/http'
import type {PayloadAction} from '@reduxjs/toolkit'
import {createAsyncThunk, createSlice} from '@reduxjs/toolkit'


type Token = string

export type Infos = {
  [index: string]: unknown
}

export type UserState = {
  token: Token
  infos: Infos
  mark?: boolean
}

type login = {
  email: string
  pass: string
}

export const loginAction = createAsyncThunk('users/loginAction', async (payload: login) => {
  const res = await http.post('users/login', payload)
  return res
})
export const infosAction = createAsyncThunk('users/infosAction', async () => {
  const res = await http.get('users/infos')
  return res
})

const usersSlice = createSlice({
  name: 'users',
  initialState: {
    token: '',
    mark: false,
    infos: {}
  } as UserState,
  reducers: {
    updateToken(state, action: PayloadAction<Token>) {
      state.token = action.payload
    },
    updateInfos(state, action: PayloadAction<Infos>) {
      state.infos = action.payload
    },
    updateMark(state, action: PayloadAction<boolean>) {
      state.mark = action.payload
    },
    clearToken(state) {
      state.token = ''
    },
  }
})


export const { updateToken, updateInfos, updateMark, clearToken } = usersSlice.actions
export default usersSlice.reducer
